<template>
  <div class="target-management-page">
    <el-card class="page-header">
      <h2>
        <el-icon><Setting /></el-icon>
        PPH目标值管理
      </h2>
      <p>设置和管理各产品在不同生产线的PPH目标值</p>
    </el-card>

    <!-- 新增目标值表单 -->
    <el-card class="add-target-form">
      <template #header>
        <span>新增PPH目标值</span>
      </template>

      <el-form
        ref="targetFormRef"
        :model="targetForm"
        :rules="targetRules"
        label-width="120px"
        @submit.prevent="submitTarget"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="物料编码" prop="material_code">
              <el-input v-model="targetForm.material_code" v-trim-input placeholder="输入物料编码" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="产品名称" prop="product_name">
              <el-input v-model="targetForm.product_name" v-trim-input placeholder="输入产品名称" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="产品系列">
              <el-input v-model="targetForm.product_series" placeholder="输入产品系列(可选)" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="* 生产线" prop="line_name">
              <el-input
                v-model="targetForm.line_name"
                placeholder="输入生产线(支持多条)"
              />
              <div class="form-tip">
                支持多条生产线，用"、"或","分隔，如：3、5 或 生产线A,生产线B
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="记录日期" prop="record_date">
              <el-date-picker
                v-model="targetForm.record_date"
                type="date"
                placeholder="选择记录日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>


          <el-col :span="6">
            <el-form-item label="* 标准人数" prop="standard_staff">
              <el-input
                v-model.number="targetForm.standard_staff"
                placeholder="输入标准人数"
                inputmode="numeric"
                clearable
              />
            </el-form-item>
          </el-col>


        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="节拍" prop="takt_time">
              <el-input-number
                v-model="targetForm.takt_time"
                placeholder="输入节拍时间"
                :min="0"
                :max="999.9"
                :precision="2"
                :step="0.1"
                :controls="true"
                :step-strictly="false"
                style="width: 100%"
                clearable
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="整机目标值">
              <el-input-number
                :model-value="computedWholeTarget"
                :min="0"
                :max="9999999"
                :precision="2"
                :step="0.01"
                :controls="false"
                disabled
                style="width: 100%"
              />
              <div class="form-tip">按公式自动计算：3600 / 人数 / 节拍</div>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="整机电机节拍">
              <el-input-number
                v-model.number="targetForm.motor_takt_time"
                placeholder="输入整机电机节拍"
                :min="0"
                :max="999.9"
                :precision="2"
                :step="0.1"
                :controls="true"
                :step-strictly="false"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="整机电机目标值">
              <el-input-number
                :model-value="computedMotorTarget"
                :min="0"
                :max="9999999"
                :precision="2"
                :step="0.01"
                :controls="false"
                disabled
                style="width: 100%"
              />
              <div class="form-tip">按公式自动计算：3600 / 人数 / 整机电机节拍</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="submitTarget" :loading="submitting">
            保存目标值
          </el-button>
          <el-button @click="resetTargetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 目标值列表 -->
    <el-card class="target-list">
      <template #header>
        <div class="list-header">
          <span>PPH目标值列表</span>
          <div class="header-actions">
            <el-button @click="exportTargets" type="success">
              <el-icon><Download /></el-icon>
              导出Excel
            </el-button>
            <el-button @click="loadTargets" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索过滤：五个条件第一行展示 -->
      <el-row :gutter="12" class="search-filters">
        <el-col :span="4">
          <el-input v-model="searchForm.material_code" v-trim-input placeholder="搜索物料编码" clearable />
        </el-col>
        <el-col :span="4">
          <el-input v-model="searchForm.product_name" v-trim-input placeholder="搜索产品名称" clearable />
        </el-col>
        <el-col :span="4">
          <LineSelector
            v-model="searchForm.line_name"
            :lines="lines"
            placeholder="筛选生产线"
            :allow-create="true"
            :clearable="true"
            :filterable="true"
          />
        </el-col>
        <el-col :span="4">
          <DateSelector
            v-model="searchForm.created_date"
            placeholder="筛选创建日期"
            :clearable="true"
          />
        </el-col>
        <el-col :span="4">
          <el-date-picker
            v-model="searchForm.record_date"
            type="date"
            placeholder="记录日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-col>
        <el-col :span="4" class="actions-col">
          <el-button @click="queryTargets" type="primary" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetFilters" type="default">重置</el-button>
        </el-col>
      </el-row>
      <!-- 第二行：新增 产品系列 筛选 -->
      <el-row :gutter="12" class="search-filters" style="margin-top: 8px;">
        <el-col :span="4">
          <el-input v-model="searchForm.product_series" placeholder="搜索产品系列" clearable />
        </el-col>
      </el-row>

      <!-- 目标值表格（支持行内编辑-逐行保存） -->
      <el-table
        :data="paginatedTargets"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        :max-height="tableMaxHeight"
      >
        <el-table-column prop="material_code" label="物料编码" width="140" />
        <el-table-column prop="product_name" label="产品名称" width="240" show-overflow-tooltip />
        <el-table-column prop="product_series" label="产品系列" width="180">
          <template #default="{ row }">
            <div v-if="!row._editing">{{ row.product_series || '' }}</div>
            <el-input
              v-else
              :model-value="row._editing?.product_series ?? row.product_series"
              @update:modelValue="(val: any) => { ensureEditing(row); row._editing.product_series = val; }"
              size="small"
              placeholder="产品系列"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column prop="line_name" label="生产线" width="120" />
        <el-table-column prop="record_date" label="记录日期" width="140">
          <template #default="{ row }">
            <div v-if="!row._editing">{{ row.record_date }}</div>
            <el-date-picker
              v-else
              :model-value="row._editing?.record_date ?? row.record_date"
              @update:modelValue="(val: any) => { ensureEditing(row); row._editing.record_date = val }"
              type="date"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              placeholder="选择日期"
              size="small"
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column prop="takt_time" label="节拍" width="120">
          <template #default="{ row }">
            <div v-if="!row._editing">{{ row.takt_time }}</div>
            <el-input-number
              v-else
              :model-value="row._editing?.takt_time ?? row.takt_time"
              @update:modelValue="(val: any) => { ensureEditing(row); row._editing.takt_time = val; updateRowTargets(row) }"
              :min="0"
              :max="999.9"
              :precision="2"
              :step="0.1"
              :controls="true"
              :step-strictly="false"
              size="small"
              placeholder="节拍"
              style="width: 100%"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column prop="whole_machine_target" label="整机目标值" width="150">
          <template #default="{ row }">
            <div v-if="!row._editing">{{ (row.whole_machine_target !== null && row.whole_machine_target !== undefined) ? Number(row.whole_machine_target).toFixed(2) : '' }}</div>
            <el-input-number
              v-else
              :model-value="row._editing?.whole_machine_target ?? row.whole_machine_target"
              :min="0"
              :max="9999999"
              :precision="2"
              :step="0.01"
              :controls="false"
              disabled
              size="small"
              placeholder="整机目标值（自动计算）"
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column prop="motor_takt_time" label="电机节拍" width="120">
          <template #default="{ row }">
            <div v-if="!row._editing">{{ row.motor_takt_time }}</div>
            <el-input-number
              v-else
              :model-value="row._editing?.motor_takt_time ?? row.motor_takt_time"
              @update:modelValue="(val: any) => { ensureEditing(row); row._editing.motor_takt_time = val; updateRowTargets(row) }"
              :min="0"
              :max="999.9"
              :precision="2"
              :step="0.1"
              :controls="true"
              :step-strictly="false"
              size="small"
              placeholder="电机节拍"
              style="width: 100%"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column prop="motor_target" label="整机电机目标值" width="170">
          <template #default="{ row }">
            <div v-if="!row._editing">{{ (row.motor_target !== null && row.motor_target !== undefined) ? Number(row.motor_target).toFixed(2) : '' }}</div>

            <el-input-number
              v-else
              :model-value="row._editing?.motor_target ?? row.motor_target"
              :min="0"
              :max="9999999"
              :precision="2"
              :step="0.01"
              :controls="false"
              disabled
              size="small"
              placeholder="电机目标值（自动计算）"
              style="width: 100%"
            />
          </template>
        </el-table-column>

        <el-table-column prop="standard_staff" label="标准人数" width="120">
          <template #default="{ row }">
            <div v-if="!row._editing">{{ row.standard_staff }}</div>
            <el-input
              v-else
              :model-value="row._editing?.standard_staff ?? row.standard_staff"
              @update:modelValue="(val: any) => { ensureEditing(row); row._editing.standard_staff = val; updateRowTargets(row) }"
              inputmode="numeric"
              size="small"
              placeholder="标准人数"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <div v-if="!row._editing">
              <el-button size="small" type="primary" @click="ensureEditing(row)">编辑</el-button>
            </div>
            <div v-else>
              <el-button size="small" type="success" @click="saveRow(row)">保存</el-button>
              <el-button size="small" @click="cancelEdit(row)">取消</el-button>
              <el-button size="small" type="danger" @click="deleteTarget(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="targets.length > 0"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="filteredTargets.length"
        :page-sizes="[20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>

  </div>
</template>

<script setup lang="ts">
import { Setting, Refresh, Download, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { formatDateTime } from '@/utils/commonUtils'


// 根据窗口高度动态设置表格最大高度，保住表头与筛选区域
const tableMaxHeight = computed(() => {
  // 预留顶部（页头+筛选+间距）约 320~380px，随窗口大小适配
  const reserve = 360
  const h = window.innerHeight || 900
  return Math.max(420, h - reserve)
})

import { pphService } from '../../services/pphService'
import { useFormDataStore } from '@/stores/formDataStore'

import DateSelector from '@/components/common/DateSelector.vue'
import LineSelector from '@/components/common/LineSelector.vue'

// 表单数据持久化store
const formDataStore = useFormDataStore()

// 状态
const loading = ref(false)
const submitting = ref(false)
const targets = ref<any[]>([])
const lines = ref<any[]>([])

const targetFormRef = ref()

// 分页
const currentPage = ref(1)
const pageSize = ref(20)

// 表单数据
const targetForm = reactive({
  material_code: '',
  product_name: '',
  product_series: '',
  line_name: '',
  record_date: '',
  takt_time: null,
  motor_takt_time: null,
  whole_machine_target: null,
  motor_target: null,
  standard_staff: null
})

// 搜索表单
const searchForm = reactive({
  material_code: '',
  product_name: '',
  product_series: '',
  line_name: '',
  record_date: '',
  created_date: ''
})

// 表单验证规则
const targetRules = {
  material_code: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],

  product_name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  line_name: [{ required: true, message: '请输入生产线', trigger: 'blur' }],
  record_date: [{ required: true, message: '请选择记录日期', trigger: 'change' }],
  // 使用el-input-number组件，支持1位小数
  takt_time: [{ validator: (_:any, v:any, cb:any) => { if (v === undefined || v === null || v === '') { cb(); return; } const n = Number(v); if (Number.isNaN(n) || n < 0.01) { cb(new Error('请输入≥0.01的数字，支持2位小数')); } else cb(); }, trigger: ['blur','change'] }],
  standard_staff: [{ required: true, validator: (_:any, v:any, cb:any) => { const n = Number(v); if(Number.isInteger(n) && n >= 1){ cb(); } else cb(new Error('请输入≥1的整数')); }, trigger: ['blur','change'] }]
}

// 计算属性 - 现在只用于显示，实际筛选在后端进行
const filteredTargets = computed(() => {
  return targets.value
})

// 分页计算属性
const paginatedTargets = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTargets.value.slice(start, end)
})

// 确保处于编辑态（为行添加 _editing 快照）
// 目标值预览（只读显示，实际以后端计算为准）
const computedWholeTarget = computed<number | null>(() => {
  const staff = Number(targetForm.standard_staff)
  const takt = targetForm.takt_time
  // 只有当节拍有值且>0，人数>0时才计算
  if (staff > 0 && takt != null && takt !== '' && Number(takt) > 0) {
    return Number((3600 / (staff * Number(takt))).toFixed(2))
  }
  return null
})
const computedMotorTarget = computed<number | null>(() => {
  const staff = Number(targetForm.standard_staff)
  const taktM = targetForm.motor_takt_time
  // 只有当电机节拍有值且>0，人数>0时才计算
  if (staff > 0 && taktM != null && taktM !== '' && Number(taktM) > 0) {
    return Number((3600 / (staff * Number(taktM))).toFixed(2))
  }
  return null
})

// 行内编辑实时计算目标值
function updateRowTargets(row: any) {
  if (!row._editing) return

  const staff = Number(row._editing.standard_staff) || 0
  const takt = row._editing.takt_time
  const motorTakt = row._editing.motor_takt_time

  // 计算整机目标值 - 只有当节拍有值且>0，人数>0时才计算
  if (staff > 0 && takt != null && takt !== '' && Number(takt) > 0) {
    row._editing.whole_machine_target = Number((3600 / (staff * Number(takt))).toFixed(2))
  } else {
    row._editing.whole_machine_target = null
  }

  // 计算电机目标值 - 只有当电机节拍有值且>0，人数>0时才计算
  if (staff > 0 && motorTakt != null && motorTakt !== '' && Number(motorTakt) > 0) {
    row._editing.motor_target = Number((3600 / (staff * Number(motorTakt))).toFixed(2))
  } else {
    row._editing.motor_target = null
  }
}

function ensureEditing(row: any) {
  if (!row._editing) {
    row._editing = {
      product_series: row.product_series ?? '',
      record_date: row.record_date,
      takt_time: row.takt_time,
      motor_takt_time: row.motor_takt_time,
      // 目标值为只读，仍然带上旧值用于对比展示
      whole_machine_target: row.whole_machine_target,
      motor_target: row.motor_target,
      standard_staff: row.standard_staff
    }
  }
}

function cancelEdit(row: any) {
  if (row && row._editing) delete row._editing
}

async function saveRow(row: any) {
  if (!row || !row.id || !row._editing) return
  try {
    loading.value = true

    // 最小校验
    if (row._editing.standard_staff != null && row._editing.standard_staff < 1) {
      ElMessage.error('标准人数必须 >= 1')
      return
    }

    // 仅发送发生变化的字段（含 record_date）
    const candidates = ['product_series','record_date','takt_time','motor_takt_time','standard_staff']
    const patch: any = {}
    for (const key of candidates) {
      if (row._editing && Object.prototype.hasOwnProperty.call(row._editing, key)) {
        const newVal = row._editing[key]
        const oldVal = row[key]
        if ((newVal ?? null) !== (oldVal ?? null)) {
          // 空串按后端约定转为 NULL
          patch[key] = (key === 'product_series') ? (newVal ?? '') : newVal
        }
      }
    }

    if (Object.keys(patch).length === 0) {
      ElMessage.info('无变更，不需要保存')
      return
    }

    const resp = await pphService.updateTarget(row.id, patch)
    if (resp && resp.success) {
      // 仅覆盖发生变化的字段
      for (const k of Object.keys(patch)) {
        if (k === 'product_series') {
          row.product_series = patch.product_series === '' ? null : patch.product_series
        } else {
          ;(row as any)[k] = (patch as any)[k]
        }
      }
      // 同步后端重算与规范化后的值（若返回）
      if (Object.prototype.hasOwnProperty.call(resp, 'whole_machine_target')) {
        row.whole_machine_target = resp.whole_machine_target
      }
      if (Object.prototype.hasOwnProperty.call(resp, 'motor_target')) {
        row.motor_target = resp.motor_target
      }
      if (Object.prototype.hasOwnProperty.call(resp, 'takt_time')) {
        row.takt_time = resp.takt_time
      }
      if (Object.prototype.hasOwnProperty.call(resp, 'motor_takt_time')) {
        row.motor_takt_time = resp.motor_takt_time
      }
      if (Object.prototype.hasOwnProperty.call(resp, 'standard_staff')) {
        row.standard_staff = resp.standard_staff
      }
      delete row._editing
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(resp?.error || '保存失败')
    }
  } catch (e: any) {
    console.error('保存行失败:', e)
    // 409 唯一冲突：给出更友好提示并提供快速筛选引导
    if (e?.response?.status === 409) {
      const apiMsg = e?.response?.data?.error || '该物料+生产线在该记录日期已存在目标值'
      await ElMessageBox.alert(
        `${apiMsg}`,
        '保存失败',
        { type: 'warning', confirmButtonText: '查看该日期记录' }
      )
      // 将当前行的查询条件回填到搜索表单，方便用户直接查询到冲突记录
      try {
        searchForm.material_code = row.material_code || ''
        searchForm.product_name = row.product_name || ''
        searchForm.line_name = row.line_name || ''
        // 优先取编辑态的日期
        const d = row._editing?.record_date || row.record_date
        searchForm.record_date = d || ''
        // 触发查询
        await queryTargets()
      } catch(_){ /* 忽略引导失败 */ }
    } else {
      ElMessage.error('保存失败: ' + (e?.message || String(e)))
    }
  } finally {
    loading.value = false
  }
}

// 方法
async function loadTargets() {
  try {
    loading.value = true
  const response = await pphService.getTargets()
  targets.value = Array.isArray(response) ? response : []
  } catch (error: any) {
  console.error('获取目标值列表失败:', error)
  ElMessage.error('获取目标值列表失败')
  } finally {
    loading.value = false
  }
}

async function loadLines() {
  try {
    const response = await pphService.getLines()
    lines.value = response.lines || []
    } catch (error: any) {
    console.error('获取生产线列表失败:', error)
      ElMessage.error('获取生产线列表失败: ' + (error?.message || String(error)))
    lines.value = []
  }
}

// 拆分生产线字段（与Excel导入逻辑一致）
function splitProductionLines(lineString: string) {
  if (!lineString || typeof lineString !== 'string') {
    return []
  }

  // 支持的分隔符：中文顿号、英文逗号、中文逗号
  const separators = ['、', ',', '，']

  for (const sep of separators) {
    if (lineString.includes(sep)) {
      return lineString.split(sep)
        .map(line => line.trim())
        .filter(line => line.length > 0)
    }
  }

  // 如果没有分隔符，返回单个生产线
  return [lineString.trim()]
}

// 前端日期规范化（与后端标准化口径一致，统一到 YYYY-MM-DD）
function normalizeDateInput(input: any): string {
  if (!input) return ''
  const raw = String(input).trim()
  if (!raw) return ''

  // Excel 序列号（4~6位纯数字且在合理范围）
  if (/^\d{4,6}$/.test(raw)) {
    const n = parseInt(raw, 10)
    if (n > 20000 && n < 80000) {
      const d = new Date((n - 25569) * 86400 * 1000)
      if (!isNaN(d.getTime())) return d.toISOString().slice(0, 10)
    }
  }

  const s = raw.replace(/[\/\.]/g, '-').replace(/\s+/g, '-')
  const parts = s.split('-').filter(Boolean)
  if (parts.length === 3) {
    let [a, b, c] = parts.map(p => parseInt(p, 10))
    let y: number, m: number, d: number
    if (parts[0].length === 4) { y = a; m = b; d = c }
    else if (parts[2].length === 4) { if (a <= 12 && b <= 31) { m = a; d = b; y = c } else { d = a; m = b; y = c } }
    else { if (a <= 12 && b <= 31) { m = a; d = b; y = c } else { y = a; m = b; d = c } if (y < 100) y += 2000 }
    if (y < 100) y += 2000
    const dt = new Date(y, (m || 0) - 1, d || 0)
    if (!isNaN(dt.getTime()) && dt.getFullYear() === y && dt.getMonth() === (m - 1) && dt.getDate() === d) {
      return `${String(y).padStart(4,'0')}-${String(m).padStart(2,'0')}-${String(d).padStart(2,'0')}`
    }
  }
  const dt = new Date(s)
  if (!isNaN(dt.getTime())) return dt.toISOString().slice(0,10)
  return raw
}

// 监听：当用户手动输入非 YYYY-MM-DD 时，自动规范化并提示
watch(() => targetForm.record_date, (v:any) => {
  if (typeof v === 'string' && v && !/^\d{4}-\d{2}-\d{2}$/.test(v)) {
    const n = normalizeDateInput(v)
    if (n && n !== v) { targetForm.record_date = n; ElMessage.info(`记录日期已自动转为 ${n}`) }
  }
})
watch(() => searchForm.record_date, (v:any) => {
  if (typeof v === 'string' && v && !/^\d{4}-\d{2}-\d{2}$/.test(v)) {
    const n = normalizeDateInput(v)
    if (n && n !== v) { searchForm.record_date = n; ElMessage.info(`查询日期已自动转为 ${n}`) }
  }
})

async function submitTarget() {
  if (!targetFormRef.value) return

  try {
    await targetFormRef.value.validate()
    submitting.value = true

    // 拆分生产线
    const lines = splitProductionLines(targetForm.line_name)

    if (lines.length === 0) {
      ElMessage.error('请输入有效的生产线')
      return
    }

    let successCount = 0
    let updateCount = 0
    let errorCount = 0
    const errors = []

    // 为每个生产线创建目标值
    for (const lineName of lines) {
      try {
        const targetData = {
          ...targetForm,
          line_name: lineName.trim()
        }

        const response = await pphService.createTarget(targetData)

        if (response.success) {
          if (response.updated) {
            updateCount++
          } else {
            successCount++
          }
        } else {
          errorCount++
          errors.push(`${lineName}: ${response.error}`)
        }
      } catch (error: any) {
        errorCount++
        errors.push(`${lineName}: ${error?.message || String(error)}`)
      }
    }

    // 显示结果
    if (errorCount === 0) {
      if (updateCount > 0 && successCount > 0) {
        ElMessage.success(`保存成功！新增 ${successCount} 条，更新 ${updateCount} 条`)
      } else if (updateCount > 0) {
        ElMessage.success(`更新成功！共更新 ${updateCount} 条记录`)
      } else {
        ElMessage.success(`新增成功！共新增 ${successCount} 条记录`)
      }
      resetTargetForm()
      await loadTargets()
    } else {
      ElMessage.error(`部分保存失败：成功 ${successCount + updateCount} 条，失败 ${errorCount} 条`)
      if (errors.length > 0) {
        console.error('保存错误详情:', errors)
      }
    }

  } catch (error: any) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    submitting.value = false
  }
}

function resetTargetForm() {
  if (targetFormRef.value) {
    targetFormRef.value.resetFields()
  }

  Object.assign(targetForm, {
    material_code: '',
    product_name: '',
    product_series: '',
    line_name: '',
    record_date: '',
    takt_time: null,
    motor_takt_time: null,
    whole_machine_target: null,
    motor_target: null,
    standard_staff: null
  })
}

async function deleteTarget(target: any) {
  try {
    await ElMessageBox.confirm(
      `确定要删除物料编码 "${target.material_code}" 在 "${target.line_name}" 的目标值吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await pphService.deleteTarget(target.id)
    ElMessage.success('目标值删除成功')

    // 删除后按当前筛选条件重新查询，并尽量保留当前页
    await queryTargets({ preservePage: true })
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 查询目标值数据
async function queryTargets(opts?: { preservePage?: boolean }) {
  try {
    loading.value = true
    const keep = !!(opts && opts.preservePage)
    const prevPage = currentPage.value

    // 构建查询参数
    const params: any = {}
    if (searchForm.material_code) params.material_code = searchForm.material_code
    if (searchForm.product_name) params.product_name = searchForm.product_name
    if (searchForm.product_series) params.product_series = searchForm.product_series
    if (searchForm.line_name) params.line_name = searchForm.line_name
    if (searchForm.record_date) params.record_date = searchForm.record_date
    if (searchForm.created_date) params.created_date = searchForm.created_date

    const data = await pphService.getTargets(params)
    targets.value = Array.isArray(data) ? data : []

    if (keep) {
      // 计算新数据的最大页数，尽量保持在原页
      const maxPage = Math.max(1, Math.ceil(targets.value.length / pageSize.value))
      currentPage.value = Math.min(prevPage, maxPage)
    } else {
      currentPage.value = 1
    }
  } catch (error: any) {
    console.error('查询目标值失败:', error)
    ElMessage.error('查询失败: ' + (error?.message || String(error)))
    targets.value = []
  } finally {
    loading.value = false
  }
}

function handleSizeChange(size: number) {
  pageSize.value = size
  currentPage.value = 1
}

function handleCurrentChange(page: number) {
  currentPage.value = page
}

// ✅ formatDateTime函数已重构到 utils/commonUtils.ts

// 重置筛选条件
function resetFilters() {
  searchForm.material_code = ''
  searchForm.product_name = ''
  searchForm.product_series = ''
  searchForm.line_name = ''
  searchForm.record_date = ''
  searchForm.created_date = ''
  targets.value = [] // 清空数据，需要用户手动查询
}

// 已移除复合筛选组件事件，统一走本页表单

// ✅ Excel导出逻辑已重构到 utils/commonUtils.ts
async function exportTargets() {
  try {
    loading.value = true

  // 按当前筛选条件拉取导出数据，确保“未查询也可导出匹配数据”
  const params: any = {}
  if (searchForm.material_code) params.material_code = searchForm.material_code
  if (searchForm.product_name) params.product_name = searchForm.product_name
  if (searchForm.product_series) params.product_series = searchForm.product_series
  if (searchForm.line_name) params.line_name = searchForm.line_name
  if (searchForm.record_date) params.record_date = searchForm.record_date
  if (searchForm.created_date) params.created_date = searchForm.created_date

  const remote = await pphService.getTargets(params)
  const dataToExport = Array.isArray(remote) ? remote : []

    if (dataToExport.length === 0) {
      ElMessage.warning('没有数据可以导出')
      return
    }

    console.log(`📊 准备导出 ${dataToExport.length} 条目标值数据`)

    // 调用后端Excel导出API
    const apiUrl = pphService.getApiUrl()
    const response = await fetch(`${apiUrl}/api/excel/export/targets`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      },
      body: JSON.stringify({ targets: dataToExport })
    })

    if (!response.ok) {
      const error = await response.json().catch(() => ({}))
      throw new Error(error.error || `导出失败: ${response.status}`)
    }

    // 获取文件名并下载
    const contentDisposition = response.headers.get('Content-Disposition')
    let filename = `PPH目标值数据_${new Date().toISOString().split('T')[0]}.xlsx`
    if (contentDisposition) {
      const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (match && match[1]) {
        filename = match[1].replace(/['"]/g, '')
      }
    }

    // 下载文件
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success(`Excel导出成功: ${filename}`)
  } catch (error: any) {
    ElMessage.error('导出失败: ' + (error?.message || String(error)))
  } finally {
    loading.value = false
  }
}

// 保存搜索表单数据
function saveSearchFormData() {
  formDataStore.saveSearchForm('target', searchForm)
  formDataStore.savePageState('targetManagement', {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    lastSearchParams: { ...searchForm }
  })
}

// 恢复搜索表单数据
function restoreSearchFormData() {
  const savedForm = formDataStore.getSearchForm('target')
  const hasValidData = savedForm && Object.keys(savedForm).some(key => {
    const value = savedForm[key]
    return value !== '' && value !== null && value !== undefined
  })

  if (hasValidData) {
    console.log('🔄 恢复目标值页面保存的搜索条件:', savedForm)
    Object.assign(searchForm, savedForm)

    const pageState = formDataStore.getPageState('targetManagement')
    if (pageState.currentPage) {
      currentPage.value = pageState.currentPage
    }
    if (pageState.pageSize) {
      pageSize.value = pageState.pageSize
    }

    ElMessage.success('已恢复上次的搜索条件，正在自动查询...')

    // 自动执行搜索，提升用户体验
    console.log('💡 搜索条件已恢复，自动执行查询')
    queryTargets()
  } else {
    console.log('📝 目标值页面没有有效的保存状态')
  }
}

// 监听搜索表单变化，自动保存
watch(() => searchForm, saveSearchFormData, { deep: true })
watch(() => currentPage.value, saveSearchFormData)
watch(() => pageSize.value, saveSearchFormData)

// 生命周期 - 只加载生产线数据，不自动加载目标值数据
onMounted(async () => {
  await loadLines()
  // 恢复搜索表单数据
  restoreSearchFormData()
})
</script>

<style scoped>
.target-management-page {
  max-width: 100%;
  margin: 0 auto;
  padding: 0 8px;
}

/* ✅ 页面头部、列表头部、搜索过滤器样式已移至公共样式 common.css */

.add-target-form {
  margin-bottom: 20px;
}

.target-list {
  margin-bottom: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.search-filters :deep(.el-form-item) {
  margin-bottom: 0;
}

.search-filters .actions-col {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: flex-start;
}
</style>
